package net.wantongtech.xa.uploadbasicinfo.service;

import com.wtkj.vo.dzzf.base.xxdl.InteractionOrgMsgReceive;
import lombok.extern.slf4j.Slf4j;
import net.wantongtech.xa.uploadbasicinfo.dao.DownloadReceiveFileDao;
import org.csource.client.FastDFSClient;
import org.csource.common.MyException;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.*;
import java.util.Date;
import java.util.List;

/**
 * 下载接收表文件服务实现
 *
 * @author MaShibo
 * 2021/3/29 0029
 */
@Slf4j
@Service
public class DownloadReceiveFileService {


    @Resource
    private DownloadReceiveFileDao downloadReceiveFileDao;


    public void downloadByBizCode(String targetPath, int count, int... bizCodes) throws IOException, MyException {

        File targetDir = new File(targetPath);
        if (!targetDir.exists() && !targetDir.mkdirs()) {
            log.error("目标路径：{}创建失败", targetDir);
            return;
        }

        if (bizCodes == null || bizCodes.length == 0) {
            log.info("未指定要下载的bizCode");
            return;
        }

        for (int bizCode : bizCodes) {


            List<InteractionOrgMsgReceive> receiveMsgList = downloadReceiveFileDao.queryReceiveMsgByBizCode(count, bizCode);
            log.info("bizCode：{}，查询到{}条接收表记录", bizCode, receiveMsgList.size());
            if (receiveMsgList.isEmpty()) {
                continue;
            }

            for (int i = 1; i <= receiveMsgList.size(); i++) {

                InteractionOrgMsgReceive receiveMsg = receiveMsgList.get(i - 1);
                String fileName = String.format("%d_%d", bizCode, i);

                File objFile = new File(targetPath, String.format("%s.obj", fileName));
                try (FileOutputStream fos = new FileOutputStream(objFile)) {
                    try (ObjectOutputStream oos = new ObjectOutputStream(fos)) {
                        oos.writeObject(receiveMsg);
                    }
                }

                if (receiveMsg.getStoreFlag() == InteractionOrgMsgReceive.STORE_FLAG_DFS) {
                    File jsonFile = new File(targetPath, String.format("%s.json", fileName));
                    FastDFSClient.downLoadFile(receiveMsg.getStorePath(), jsonFile, null);
                }
            }
        }
        log.info("生成完成");
    }


    public void loadReceiveData(String targetPath) {
        File targetDir = new File(targetPath);
        if (!targetDir.exists()) {
            log.info("目标路径：{}不存在，不能读取数据", targetDir);
            return;
        }

        File[] objFileArr = targetDir.listFiles((dir, name) -> name.endsWith(".obj"));
        if (objFileArr == null || objFileArr.length == 0) {
            return;
        }

        log.info("共有{}个对象文件待处理", objFileArr.length);


        for (File objFile : objFileArr) {

            try {

                loadObjFile(objFile);

            } catch (Exception e) {
                log.error(e.getMessage(), e);
            }
        }
    }

    private void loadObjFile(File objFile) throws IOException, ClassNotFoundException, MyException {

        InteractionOrgMsgReceive receiveMsg = restoreReceiveObj(objFile);

        if (receiveMsg == null) {
            return;
        }

        String fileName = objFile.getName();
        String fileNameWithOutExt = fileName.substring(0, fileName.lastIndexOf('.'));

        File jsonFile = new File(objFile.getParentFile(), String.format("%s.json", fileNameWithOutExt));
        if (jsonFile.exists()) {
            String dfsStorePath = FastDFSClient.uploadFile(jsonFile);
            log.info("文件上传FastDFS成功，返回路径：{}", dfsStorePath);

            receiveMsg.setStorePath(dfsStorePath);
            receiveMsg.setCreateOn(new Date());
            downloadReceiveFileDao.createValueObject(receiveMsg);
            log.info("接收表记录保存成功");

        } else {
            log.info("json文件：{}，不存在", jsonFile);
        }
    }


    private static InteractionOrgMsgReceive restoreReceiveObj(File objFile) throws IOException, ClassNotFoundException {
        try (FileInputStream fin = new FileInputStream(objFile)) {
            try (BufferedInputStream bin = new BufferedInputStream(fin)) {
                try (ObjectInputStream oin = new ObjectInputStream(bin)) {
                    Object obj = oin.readObject();
                    if (obj instanceof InteractionOrgMsgReceive) {
                        return (InteractionOrgMsgReceive) obj;
                    }
                }
            }
        }
        return null;
    }

    public static void main(String[] args) {
        File targetDir = new File("C:\\Users\\Administrator\\Desktop\\localStorePath");

        File[] objFiles = targetDir.listFiles((dir, name) -> name.endsWith(".obj"));
        if (objFiles == null || objFiles.length == 0) {
            return;
        }

        for (File objFile : objFiles) {
            String fileName = objFile.getName();
            String fileNameWithOutExt = fileName.substring(0, fileName.lastIndexOf('.'));
            File jsonFile = new File(objFile.getParentFile(), String.format("%s.json", fileNameWithOutExt));
            if (jsonFile.exists()) {
                try {
                    InteractionOrgMsgReceive receiveObj = restoreReceiveObj(objFile);
                    if (receiveObj == null) {
                        continue;
                    }
                    Long conMsgId = receiveObj.getConMsgID();
                    log.info("conMsgId: {}", conMsgId);
                    File newFile = new File(jsonFile.getParentFile(), String.format("%d_%s.json", receiveObj.getBizCode(), receiveObj.getConMsgID()));
                    boolean result = jsonFile.renameTo(newFile);
                    if (result) {
                        log.info("重命名成功");
                    }
                } catch (Exception e) {
                    log.error(e.getMessage(), e);
                }
            }
        }
    }
}
